package com.zretc.emptraining.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.emptraining.dbtools.AjaxResponse;
import com.zretc.emptraining.dbtools.PageData;
import com.zretc.emptraining.entity.CoursePlan;
import com.zretc.emptraining.service.CoursePlanService;
import com.zretc.emptraining.service.RefTableService;
import com.zretc.emptraining.serviceimpl.CoursePlanServiceImpl;
import com.zretc.emptraining.serviceimpl.RefTableServiceImp;


/**
 * Servlet implementation class CoursePlanServlet
 */
@WebServlet("/CoursePlanServlet")
public class CoursePlanServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	CoursePlanService cps = new CoursePlanServiceImpl();
	RefTableService rtsi = new RefTableServiceImp();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CoursePlanServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码 防止中文乱码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 获取动作
		String op = "";
		// 储存动作
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("queryByPage".equals(op)) {
			// 模糊查询+分页
			doQueryByPage(request, response);
		} else if ("add".equals(op)) {
			// 增加课程计划
			doAdd(request, response);
		} else if ("del".equals(op)) {
			// 删除课程计划
			doDel(request, response);
		} else if ("upd".equals(op)) {
			// 修改课程
			doUpd(request, response);
		} else if ("ajaxReq".equals(op)) {
			ajaxReq(response);
		} else if ("totdayplan".equals(op)) {
			// 今日课程
			todayCourse(request, response);
		}
	}

	private void todayCourse(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("到了这里");
		Date date = new Date();
		SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd");
		String today = dd.format(date);
		Date t = null;
		try {
			t = dd.parse(today);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<CoursePlan> list = new ArrayList<CoursePlan>();
		PageData<CoursePlan> pd1 = cps.getAllCoursePlansByPage(1, 10000);

		for (int i = 0; i < pd1.getData().size(); i++) {
			Date start = pd1.getData().get(i).getCourseStart();
			Date end = pd1.getData().get(i).getCourseEnd();
			if (start.before(t) && end.after(t)) {
				list.add(pd1.getData().get(i));
			}
		}
		PageData<CoursePlan> pd = new PageData<CoursePlan>();
		pd.setData(list);
		// 传递PageDate对象给JSP
		request.setAttribute("pd", pd);
		// 跳转页面 转发 带request的参数
		request.getRequestDispatcher("welcome.jsp").forward(request, response);
	}

	private void ajaxReq(HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		List<CoursePlan> list = cps.getCoursePlan();
		Gson gson = new Gson();
		String jsonString = gson.toJson(list);
		PrintWriter out = response.getWriter();
		// 打印
		out.print(jsonString);
		// 关闭
		out.close();
	}

	/**
	 * 分页+查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws ParseException
	 */
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doUpdateCoursePlanStatus();
		// 分页对象
		PageData<CoursePlan> pd = null;
		// 页码默认为1
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}

		// 如果查询输入框不为空
		if (request.getParameter("teacherNo") != null && request.getParameter("teacherNo") != "") {
			String teacherNostr = request.getParameter("teacherNo");
			int teacherNo = Integer.parseInt(teacherNostr);
			// 调用Service方法
			pd = cps.getCoursePlansByPage(page, pageSize, teacherNo);
			// 将查询的教员号传回JSP
			request.setAttribute("teacherNo", teacherNo);
		} else {
			// 调用Service方法
			pd = cps.getAllCoursePlansByPage(page, pageSize);
		}

		// 传递PageDate对象给JSP
		request.setAttribute("pd", pd);
		// 跳转页面 转发 带request的参数
		request.getRequestDispatcher("CoursePlan.jsp").forward(request, response);
	}

	/**
	 * 增加课程计划
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws ParseException
	 */
	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取文本框的值
		String courseNostr = request.getParameter("courseNo");
		String courseStartstr = request.getParameter("courseStart");
		String courseEndstr = request.getParameter("courseEnd");
		String teacherNostr = request.getParameter("teacherNo");
		String courseNumstr = request.getParameter("courseNum");
		String coursePlace = request.getParameter("coursePlace");
		String courseTime = request.getParameter("courseTime");
		String courseStatusstr = request.getParameter("courseStatus");

		// 强制类型转化
		int courseNo = Integer.parseInt(courseNostr);
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
		Date courseStart = null;
		try {
			courseStart = simple.parse(courseStartstr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Date courseEnd = null;
		try {
			courseEnd = simple.parse(courseEndstr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int teacherNo = Integer.parseInt(teacherNostr);
		int courseNum = Integer.parseInt(courseNumstr);
		int courseStatus = Integer.parseInt(courseStatusstr);

		// 初始化课程对象
		CoursePlan cp = new CoursePlan(1, courseNo, courseStart, courseEnd, teacherNo, courseNum, coursePlace,
				courseTime, courseStatus);
		// 调用service的增加方法
		boolean flag = cps.addCoursePlan(cp);

		System.out.println(flag);
		// 默认 添加失败
		String msg = "添加失败!";
		int code = 0;
		// 类型名 不存在
		if (flag) {
			msg = "添加成功!";
			code = 1;
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 5将msg1转换为JSON格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		// 6 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		// 7.关闭
		out.close();
	}

	/**
	 * 删除课程计划
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 接收课程计划编号
		String cpNostr = request.getParameter("cpNo");
		// 强制转型
		int cpNo = Integer.parseInt(cpNostr);
		// 调用service的删除方法
		boolean flag = cps.delCoursePlan(cpNo);
		// 默认 删除失败
		String msg = " 删除失败！";
		int code = 0;
		// 类型名 不存在
		if (flag) {
			msg = "删除成功！";
			code = 1;
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 5将msg1转换为JSON格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		// 6 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		// 7.关闭
		out.close();
	}

	/**
	 * 修改课程计划
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doUpd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取文本框的值
		String cpNostr = request.getParameter("cpNo");
		String courseNostr = request.getParameter("courseNo");
		String courseStartstr = request.getParameter("courseStart");
		String courseEndstr = request.getParameter("courseEnd");
		String teacherNostr = request.getParameter("teacherNo");
		String courseNumstr = request.getParameter("courseNum");
		String coursePlace = request.getParameter("coursePlace");
		String courseTime = request.getParameter("courseTime");
		String courseStatusstr = request.getParameter("courseStatus");

		// 强制类型转化
		int cpNo = Integer.parseInt(cpNostr);
		int courseNo = Integer.parseInt(courseNostr);
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
		Date courseStart = null;
		try {
			courseStart = simple.parse(courseStartstr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Date courseEnd = null;
		try {
			courseEnd = simple.parse(courseEndstr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int teacherNo = Integer.parseInt(teacherNostr);
		int courseNum = Integer.parseInt(courseNumstr);
		int courseStatus = Integer.parseInt(courseStatusstr);

		// 初始化课程对象
		CoursePlan cp = new CoursePlan(cpNo, courseNo, courseStart, courseEnd, teacherNo, courseNum, coursePlace,
				courseTime, courseStatus);
		// 调用service的增加方法
		boolean flag = cps.updCoursePlan(cp);
		// 默认 修改失败
		String msg = " 修改失败！";
		int code = 0;
		// 类型名 不存在
		if (flag) {
			msg = "修改成功！";
			code = 1;
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 5将msg1转换为JSON格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		System.out.println("hahahhah");
		// 6 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		// 7.关闭
		out.close();
	}
	// 每次点击课程计划页面时走这个方法
	private void doUpdateCoursePlanStatus() {
		PageData<CoursePlan> pd = null;
	    // 页码默认为1
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 1000;
	    pd = cps.getAllCoursePlansByPage(page, pageSize);
	    System.out.println(pd.getData());
		// 获取今天的时间  获取所有的开课时间
		Date today = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String n = sf.format(today);
		System.out.println(n);
		Date now = null;
		try {
			now = sf.parse(n);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i = 0; i < pd.getData().size(); i++) {
			Date start = pd.getData().get(i).getCourseStart();
			Date end = pd.getData().get(i).getCourseEnd();
			String st = sf.format(start);
			int cpNo = pd.getData().get(i).getCpNo();
			int courseNum = pd.getData().get(i).getCourseNum();
			int refNum = rtsi.getCountByCPNo(cpNo);
			int status = pd.getData().get(i).getCourseStatus();
			if(st.equals(n)) {
				// 当天  修改开课状态  为 进行中  或者 已取消
				// 1.获取计划人数    2.获取参培人数
				if((courseNum/2) > refNum) {
					// 状态修改为已取消 4 -- 通过课程计划号 修改
					cps.updCoursePlanStatus(cpNo, 4);
				}else {
					// 状态修改为进行中 2 -- 通过课程计划号 修改
					cps.updCoursePlanStatus(cpNo, 2);
				}
			}else if(end.before(now) && status != 4) {
				// 状态修改为已结束 3 -- 通过课程计划号 修改
				cps.updCoursePlanStatus(cpNo, 3);
			}else if(start.after(now)) {
				if(courseNum == refNum) {
					// 状态修改为已满员  5
					cps.updCoursePlanStatus(cpNo, 5);
				}else {
					// 状态修改为招募中 1
					cps.updCoursePlanStatus(cpNo, 1);
				}
			}else if(start.before(now)&&end.after(now)) {
				// 状态修改为进行中 2 -- 通过课程计划号 修改
				cps.updCoursePlanStatus(cpNo, 2);
			}
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
